package com.xtaller.easy.admin.controller.sys;

import com.alibaba.fastjson.JSONObject;
import com.xtaller.common.convert.J;
import com.xtaller.common.convert.L;
import com.xtaller.common.convert.V;
import com.xtaller.common.kit.TimeKit;
import com.xtaller.easy.admin.base.TApi;
import com.xtaller.easy.admin.config.R;
import com.xtaller.easy.admin.model.SysMenu;
import com.xtaller.easy.admin.model.SysMenuAuth;
import com.xtaller.easy.admin.service.impl.SysMenuAuthService;
import com.xtaller.easy.admin.service.impl.SysMenuService;
import com.xtaller.easy.admin.specification.MenuAuthOpt;
import com.xtaller.easy.admin.specification.MenuCreate;
import com.xtaller.easy.admin.specification.MenuUpdate;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Taller on 2018/4/23
 */
@Api(tags = "权限菜单api")
@RestController
@RequestMapping("/v1/sys")
@CrossOrigin   //跨域服务注解
public class MenuApi extends TApi {
    @Autowired
    private SysMenuAuthService menuAuthService;

    private Map<String, String> BaseVerify() {
        Map<String, String> verify = new HashMap<>();
        verify.put("name", "系统模块名称不能为空");
        return verify;
    }

    @GetMapping("/menu")
    @ApiOperation(value = "读取所有模块菜单数据")
    public Object getMenu() {
        // 数据组装生成树
        List<JSONObject> data = menuService.getMenu();
        if(data.size() > 0){
            for(JSONObject object:data){
                object.put("menus", L.list2Tree(J.o2l(object.get("menus")), "0"));
            }
        }
        return R.ok(data);
    }

    @GetMapping("/menu/{moduleId}")
    @ApiOperation(value = "读取权限菜单数据列表")
    public Object getMenuTreeByModuleId(@PathVariable("moduleId") Long moduleId) {
        return R.ok(menuService.getMenuTreeByModuleId(moduleId));
    }

    @PostMapping("/menu")
    @ApiOperation(value = "创建权限菜单")
    public Object createMenu(@RequestBody MenuCreate object) {
        JSONObject check = V.checkEmpty(BaseVerify(), object);
        if (check.getBoolean("check"))
            return R.error(check.getString("message"));
        SysMenu module = J.o2m(object, SysMenu.class);
        module.setCreator(getUserIdByToken());
        // 唯一性判断
        if (menuService.existName(module, true))
            return R.error("权限菜单名称已经存在请更换");

        module = menuService.createSysMenu(module);
        if (module == null)
            return R.error("创建权限菜单失败,请稍后再试");
        return R.ok("创建权限菜单成功", formatObject(module));
    }

    @PutMapping("/menu")
    @ApiOperation(value = "创建权限菜单")
    public Object updateMenu(@RequestBody MenuUpdate object) {
        if(object.getId() == null)
            return R.error("数据Id不能为空");
        if(menuService.selectById(object.getId()) == null)
            return R.error("数据Id异常");
        JSONObject check = V.checkEmpty(BaseVerify(), object);
        if (check.getBoolean("check"))
            return R.error(check.getString("message"));
        SysMenu module = J.o2m(object, SysMenu.class);
        module.setReviser(getUserIdByToken());
        // 唯一性判断
        if (menuService.existName(module, false))
            return R.error("权限菜单名称已经存在请更换");

        module = menuService.updateSysMenu(module);
        if (module == null)
            return R.error("修改权限菜单失败,请稍后再试");
        return R.ok("修改权限菜单成功", formatObject(module));
    }

    @DeleteMapping("/menu/{id}")
    @ApiOperation(value = "删除权限菜单数据")
    public Object deleteMenu(@PathVariable("id") String id) {
        if(menuService.selectById(id) == null)
            return R.error("数据Id异常");
        boolean check = menuService.isDelete(id);
        if(check)
            return R.error("该权限菜单下有菜单数据，禁止删除！");
        if(menuService.deleteSysMenu(id, getUserIdByToken()))
            return R.ok("权限菜单删除成功");
        return R.error("删除失败请稍后再试");
    }

    @PutMapping("/menu/auth/{menuId}")
    @ApiOperation(value = "配置菜单按钮权限")
    public Object setMenuAuth(
            @PathVariable("menuId") String menuId,
            @RequestBody List<MenuAuthOpt> object){
        if(object.size() == 0){
            menuAuthService.initAuthByMenuId(
                    getUserIdByToken(),
                    TimeKit.getTimestamp(),
                    menuId
                    );
            return R.ok("清空配置成功");
        }else {
            List<SysMenuAuth> auths = new ArrayList<>();
            for (MenuAuthOpt model : object) {
                SysMenuAuth auth = J.o2m(model, SysMenuAuth.class);
                auth.setCreator(getUserIdByToken());
                auths.add(auth);
            }

            boolean ok = false;
            try {
                ok = menuAuthService.setAuth(auths);
            } catch (Exception e) {

            }
            if (ok)
                return R.ok("配置成功");
            return R.error("配置失败");
        }
    }

    @GetMapping("/menu/auth/{menuId}")
    @ApiOperation(value = "根据菜单id获取配置的权限按钮信息")
    public Object getAuthByMenuId(@PathVariable("menuId") String menuId){
        return R.ok(menuAuthService.getAuthByMenuId(menuId));
    }
}

